import traceback
import arrow

from pymongo import MongoClient, UpdateOne

from conf.settings import CLOUDMONITOR_MONGODB
from utility.utils import trans_interval
from utility.log import Logger

logger = Logger().get_logger()


db = MongoClient(CLOUDMONITOR_MONGODB)['cloudmonitor-dev2']


def main():
    logger.info("————Start————")
    t0 = arrow.utcnow()
    query = {'taskSettings.interval': {'$type': 'object'}}
    total = db['tasks'].count_documents(query)
    i = 0

    while item := db['tasks'].find_one(query):
        try:
            interval = item['taskSettings']['interval']
            _temp_query = {'taskSettings.interval.unit': interval['unit'], 'taskSettings.interval.num': interval['num']}
            new_interval = trans_interval(interval)
            results = db['tasks'].update_many(_temp_query, {'$set': {'taskSettings.interval': new_interval}})
            i += results.raw_result.get('nModified')

            logger.info(f"{i/total*100}% "
                        f"trans interval {{unit: {interval['unit']}, num: {interval['num']}}} to {new_interval}.")
        except Exception as e:
            traceback.print_exc()

    logger.info(f"Finish, costs {arrow.utcnow()-t0}")


if __name__ == '__main__':
    main()
